#include "Settings.h"
#include <windows.h>
#include <stdio.h>
#include "libjson.h"
#include <fstream>
#include <Shlobj.h>

namespace SubPlayer
{
    const wstring Settings::appDir = L"\\SubPlayer\\";
    const wstring Settings::ConfFileName = L"settings.json";

    Settings::Settings():
    encoding(L"UNICODE"), //:TODO just temporaly.
    locale(_wsetlocale(LC_ALL, NULL)),
    dllLocation(GetExecutionPath())
    {
        string fileString;
        if (ReadConfFileToString(fileString) != 0 || fileString.size() == 0) {
            //If file cannot be read, lets all settings have their default value, which is set in initialization list
            return;
        }
        try {
            JSONNode jNode = libjson::parse(libjson::to_json_string(fileString));
            
            #ifdef _DEBUG
            std::wcout << jNode.size() << endl;//reader.getFormattedErrorMessages();
            #endif
        }
        catch (std::invalid_argument ex) {
            //if parsing fails all options should stay at their default value
            return;
        }
        //    SetDefaultValues();
        //}
    }

    void Settings::SetDefaultValues()
    {
    }

    wstring Settings::GetExecutionPath()
    {
        wstring fullPath;                                       //will hold full path to exe file of this program
        wchar_t* dir = new wchar_t[MAX_PATH];                   //will hold only path f.e. C:\programs\subs.exe -> \programs\ 
        wchar_t* driveChar = new wchar_t[3];                    //will hold driveChar (one letter) + colon + trailing char + 3 letters

        fullPath.resize(MAX_PATH);
        GetModuleFileNameW(NULL, &fullPath[0], 1000);
        fullPath.shrink_to_fit();
        _wsplitpath_s(fullPath.c_str(), driveChar, 3, dir, MAX_PATH, NULL, 0, NULL, 0);
        //I will return concatenation of drive and path. I need to retype one of the wchar_t strings to wstring to be able to use + operator
        return wstring(driveChar) + dir;
    }

    int Settings::ReadConfFileToString(string& fileString)
    {
        PWSTR path;
        if (SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &path) != S_OK) {
            CoTaskMemFree(path);
            return 1;
        }
        wstring confPath(path + appDir + ConfFileName);
        CoTaskMemFree(path);
        std::ifstream fileStream(confPath);
        if (fileStream.bad()) {
            return 2;
        }
        fileString = string((std::istreambuf_iterator<char>(fileStream)), std::istreambuf_iterator<char>()); 
        return 0;
    }
}